package com.dianping.index;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.TermDocs;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.index.TermPositions;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class ReadIndex
{
    private static final String INDEX_DIR="E:\\index";
    public static void main(String[] args){
        long startRead = System.currentTimeMillis();
        readIndex(new File(INDEX_DIR));
        long finishRead = System.currentTimeMillis();
    }
    
    public static void readIndex(File indexDir){
        try
        {
            Directory directory = FSDirectory.open(indexDir);
            IndexReader indexReader = IndexReader.open(directory);
            System.out.println(indexReader.numDocs());
            for(int i=0;i<indexReader.numDocs();i++){
                System.out.println(indexReader.document(i));
            }
            
            TermEnum termEnum = indexReader.terms();
            while(termEnum.next()){
                System.out.println(termEnum.term());
                System.out.println(termEnum.docFreq());
                
               // TermPositions termPositions = indexReader.termPositions(termEnum.term());
                
                TermDocs termDocs = indexReader.termDocs(termEnum.term());
                while(termDocs.next()){
                    System.out.println("DocNo:"+termDocs.doc()+",Freq:"+termDocs.freq());
                }
            }
            for(int j=0;j<indexReader.numDocs();j++){
                TermFreqVector termFreqVector = indexReader.getTermFreqVector(j, "contents");
                if(termFreqVector==null){
                    System.out.println("termFreqVector is null");
                    continue;
                }
                String fieldName=termFreqVector.getField();
                String[] terms = termFreqVector.getTerms();
                int[] frequences = termFreqVector.getTermFrequencies();
                
                System.out.println("FieldName:"+fieldName);
                for(int k=0;k<terms.length;k++){
                    System.out.println("["+terms[k]+":"+frequences[k]+"]");
                }
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
